package com.credit.mola.app.ui.process.page

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.credit.mola.app.R
import com.credit.mola.app.adapter.OcrTypeAdapter
import com.credit.mola.app.databinding.PageOcrBinding
import com.credit.mola.app.pro.ProFragment
import com.credit.mola.app.ui.process.activity.CameraOcrActivity
import com.credit.mola.app.ui.process.activity.ProcessActivity
import com.credit.mola.app.utils.DensityUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.dialog.PhotoDialog
import com.credit.mola.app.utils.dialog.SubmitSuccessDialog
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.event.track.TrackEventManager
import com.credit.mola.app.utils.gilde.ImageUtil
import com.credit.mola.app.utils.helper.CustomConfigHelper
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.AppUrls.addCommonParams
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.app.utils.imagecovert.ImageConvert
import com.credit.mola.app.utils.log.HHLog
import com.credit.mola.app.utils.rv.LinearDecoration
import com.credit.mola.lib_baseadapter.SikadwaOnItemChildClickListener
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/19 16:49
 * @Annotation：流程 - 证件照
 */
class OcrPage(): ProFragment() {

    private var _binding: PageOcrBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var stepItem: JSONObject? = null

    //类型列表
    private val typeIconNormalList = arrayListOf(R.mipmap.img_ocr_idcard_normal,R.mipmap.img_ocr_passport_normal,R.mipmap.img_ocr_drving_license_normal,R.mipmap.img_ocr_election_card_normal,R.mipmap.img_ocr_no_documents_normal)
    private val typeIconSelectList = arrayListOf(R.mipmap.img_ocr_idcard_select,R.mipmap.img_ocr_passport_select,R.mipmap.img_ocr_drving_license_select,R.mipmap.img_ocr_election_card_select,R.mipmap.img_ocr_no_documents_select)
    private val typeTitleList = arrayListOf(R.string.process_ocr_idcard,R.string.process_ocr_passport,R.string.process_ocr_drving_license,R.string.process_ocr_election_card,R.string.process_ocr_no_documents)
    private val typeList = arrayListOf("IDCARD","PASSPORT","DRIVING","ELECTIONCARD","NONE")

    //身份验证类型
    private var mTypeAdapter: OcrTypeAdapter? = null
    private var selectItem: JSONObject? = null
    //是否选中删除信息,默认选中
    private var isSelectedDelete = true

    //是否是正面
    private var isFront = true
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    constructor(data: JSONObject): this(){
        this.stepItem = data
    }

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageOcrBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        isSelectedDelete = true
        showSelectedDeleteViewTips()
        initRecyclerView()
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        showSikadwaSelectedImageCallback(localPath)
                    }
                }
            } else {
                HHLog.e("No media selected")
            }
        }
        EventBus.getDefault().register(this)
        //不显示下一步
        _binding?.btnNext?.visibility = View.GONE
    }

    override fun initListener() {
        //切换是否选中删除个人信息
        _binding?.deleteTipsLayout?.setOnClickListener {
            isSelectedDelete = !isSelectedDelete
            showSelectedDeleteViewTips()
        }

        //idcard 正面
        _binding?.ocrIdCardLayout?.frontLayout?.setOnClickListener { onSikadwaUpdateClickListener(it) }
        //idcard 反面
        _binding?.ocrIdCardLayout?.backLayout?.setOnClickListener { onSikadwaUpdateClickListener(it) }
        //护照 正面
        _binding?.ocrPassportLayout?.imgView?.setOnClickListener { onSikadwaUpdateClickListener(it) }
        //驾驶证 正面
        _binding?.ocrDriverLicenseLayout?.frontLayout?.setOnClickListener { onSikadwaUpdateClickListener(it) }
        //驾驶证 反面
        _binding?.ocrDriverLicenseLayout?.backLayout?.setOnClickListener { onSikadwaUpdateClickListener(it) }
        //选举卡 正面
        _binding?.ocrElectionCardLayout?.frontLayout?.setOnClickListener { onSikadwaUpdateClickListener(it) }
        //选举卡 反面
        _binding?.ocrElectionCardLayout?.backLayout?.setOnClickListener { onSikadwaUpdateClickListener(it) }

        //下一步
        _binding?.btnNext?.setOnClickListener {
            onSikadwaSubOcrDataAction()
        }
    }

    override fun initData() {
        stepItem?.let {
            addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_START,it.optString("stepTitle")),"")
        }

        var ocrTypeSize = typeTitleList.size
        //从配置中获取是否支持不传证件照
        //是否支持选择不传证件照
        val isNoDocuments = CustomConfigHelper.getCmOcrNoDocuments()
        if (!isNoDocuments){
            ocrTypeSize -= 1
        }

        val dataList = arrayListOf<JSONObject>()
        for (i in 0..< ocrTypeSize){
            val obj = JSONObject()
            obj.put("isSelect",i == 0)
            obj.put("normalIconId",typeIconNormalList[i])
            obj.put("selectIconId",typeIconSelectList[i])
            obj.put("title",requireContext().getString(typeTitleList[i]))
            obj.put("type",typeList[i])
            dataList.add(obj)
        }
        mTypeAdapter?.data = dataList
        selectItem = dataList[0]
        showContentView()

        val showApprovedKey1 = getString(R.string.process_face_submit_approved_tips_over)
        val showApprovedKey2 = getString(R.string.process_face_submit_approved_tips_days)
        val showApprovedText = String.format(getString(R.string.process_face_submit_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(ContextCompat.getColor(requireContext(),R.color.FF00CB48)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(ContextCompat.getColor(requireContext(),R.color.FF00CB48)), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textIdCardApproved?.text = approvedTipsSpannable

        //支持不上传证件照
        if (isNoDocuments){
            stepItem?.let {
                val creditLimitAmount = it.optString("limitAmount")
                val showTipsKey1 = String.format(getString(R.string.process_ocr_upload_limit_add_tips_key1),creditLimitAmount)
                val showTipsKey2 = getString(R.string.process_ocr_upload_limit_add_tips_key2)
                val showTipsText = String.format(getString(R.string.process_ocr_upload_limit_add_tips),showTipsKey1,showTipsKey2)
                val startTipsIndex1 = showTipsText.indexOf(showTipsKey1)
                val startTipsIndex2 = showTipsText.indexOf(showTipsKey2)
                val creditLimitTipsSpannable = SpannableString(showTipsText)
                creditLimitTipsSpannable.setSpan(ForegroundColorSpan(ContextCompat.getColor(requireContext(),R.color.FFFF7226)), startTipsIndex1, startTipsIndex1 + showTipsKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                creditLimitTipsSpannable.setSpan(ForegroundColorSpan(ContextCompat.getColor(requireContext(),R.color.FFFF7226)), startTipsIndex2, startTipsIndex2 + showTipsKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                //加粗
                creditLimitTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startTipsIndex1, startTipsIndex1 + showTipsKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                creditLimitTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startTipsIndex2, startTipsIndex2 + showTipsKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                _binding?.ocrNoDocumentsLayout?.textNoDocumentsTips?.text = creditLimitTipsSpannable
            }
        }
    }

    /**
     * 初始化绑卡列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initRecyclerView() {
        _binding?.rvType?.setHasFixedSize(true)
        _binding?.rvType?.isNestedScrollingEnabled = false
        _binding?.rvType?.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvType?.layoutManager = layoutManager
        mTypeAdapter = OcrTypeAdapter(_binding?.rvType)
        val topDecoration = DensityUtils.dp2px(12f)
        _binding?.rvType?.addItemDecoration(LinearDecoration(0, topDecoration, 0, 0))
        _binding?.rvType?.adapter = mTypeAdapter
        _binding?.rvType?.itemAnimator = DefaultItemAnimator()
        mTypeAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.itemLayout) {
                mTypeAdapter?.let {
                    val item = it.getItem(position)
                    if (item.optBoolean("isSelect", false)) {
                        return@SikadwaOnItemChildClickListener
                    }
                    selectItem = item
                    addEvent(String.format(EventType.CLICK.CLICK_STEP_OCR_XX_SELECT,item.optString("type")),"")
                    for (i in 0..< it.itemCount){
                        val obj = it.getItem(i)
                        obj.put("isSelect",i == position)
                    }
                    it.notifyDataSetChanged()
                    showContentView()
                }
            }
        })
    }

    private fun showSelectedDeleteViewTips(){
        when(isSelectedDelete){
            true -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_selected)
            }
            else -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_normal)
            }
        }
    }

    /**
     * 提交数据
     */
    private fun onSikadwaSubOcrDataAction(){
        if (selectItem == null){
            return
        }
        var ocrType = ""
        selectItem?.let {
            ocrType = it.optString("type")
        }
        TrackEventManager.trackEventNow(String.format(EventType.CLICK.CLICK_STEP_OCR_XX_NEXT,ocrType),"")

        if (!isSikadwaOcrSubmit()){
            showToast(getString(R.string.tips_submit_error))
            return
        }
        //如果是选举卡类型，需要按照身份证类型上传
        if (ocrType == "ELECTIONCARD"){
            ocrType = "IDCARD"
        }
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.OCR_INFO)
            put("cardType",ocrType)//证件类型（PASSPORT、IDCARD、DRIVING、FACE、NONE）
        }
        if (imgFrontUrl.isNotEmpty()){
            params.put("cardImgUrl",imgFrontUrl)//证件图片正面
        }
        if (imgBackUrl.isNotEmpty()){
            params.put("cardBackImgUrl",imgBackUrl)//证件图片反面
        }

        if (isSelectedDelete){
            showIdCardSubmitDeleteInformationTipsDialog(params)
        } else {
            val act = context as ProcessActivity
            act.submitAction(params)
        }
    }

    /**
     * 检查是否填写完整
     */
    private fun isSikadwaOcrSubmit(): Boolean{
        selectItem?.let {
            val ocrType = it.optString("type")
            //支持不选证件照
            if (ocrType == "NONE"){
                return true
            }
        }
        if (imgFrontUrl.isEmpty() || selectItem == null){
            return false
        }
        selectItem?.let {
            val ocrType = it.optString("type")
            if (imgBackUrl.isEmpty() && (ocrType == "DRIVING" || ocrType == "IDCARD" || ocrType == "ELECTIONCARD")){
                return false
            }
        }
        return true
    }

    /**
     * 切换类型，显示内容
     */
    private fun showContentView(){
        imgFrontUrl = ""
        imgBackUrl = ""
        _binding?.let { binding ->
            //删除提示
            binding.deleteTipsLayout.visibility = View.VISIBLE
            binding.submitApprovedTipsLayout.visibility = View.VISIBLE

            //IdCard
            binding.ocrIdCardLayout.ocrIdCardLayout.visibility = View.GONE
            binding.ocrIdCardLayout.imgFront.setImageResource(R.mipmap.img_ocr_front)
            binding.ocrIdCardLayout.maskFront.visibility = View.GONE
            binding.ocrIdCardLayout.imgUploadFront.setImageResource(R.mipmap.img_ocr_upload)
            binding.ocrIdCardLayout.textUploadFront.text = getString(R.string.process_ocr_upload)
            binding.ocrIdCardLayout.textUploadFront.setTextColor("#FF999999".toColorInt())
            binding.ocrIdCardLayout.imgBack.setImageResource(R.mipmap.img_ocr_back)
            binding.ocrIdCardLayout.maskBack.visibility = View.GONE
            binding.ocrIdCardLayout.imgUploadBack.setImageResource(R.mipmap.img_ocr_upload)
            binding.ocrIdCardLayout.textUploadBack.text = getString(R.string.process_ocr_upload)
            binding.ocrIdCardLayout.textUploadBack.setTextColor("#FF999999".toColorInt())

            //PASSPORT
            binding.ocrPassportLayout.ocrPassportLayout.visibility = View.GONE
            binding.ocrPassportLayout.imgView.setImageResource(R.mipmap.img_ocr_front)
            binding.ocrPassportLayout.maskView.visibility = View.GONE
            binding.ocrPassportLayout.imgUpload.setImageResource(R.mipmap.img_ocr_upload)
            binding.ocrPassportLayout.textUpload.text = getString(R.string.process_ocr_upload)
            binding.ocrPassportLayout.textUpload.setTextColor("#FF999999".toColorInt())

            //DRIVING
            binding.ocrDriverLicenseLayout.ocrDriverLicenseLayout.visibility = View.GONE
            binding.ocrDriverLicenseLayout.imgFront.setImageResource(R.mipmap.img_ocr_front)
            binding.ocrDriverLicenseLayout.maskFront.visibility = View.GONE
            binding.ocrDriverLicenseLayout.imgUploadFront.setImageResource(R.mipmap.img_ocr_upload)
            binding.ocrDriverLicenseLayout.textUploadFront.text = getString(R.string.process_ocr_upload)
            binding.ocrDriverLicenseLayout.textUploadFront.setTextColor("#FF999999".toColorInt())
            binding.ocrDriverLicenseLayout.imgBack.setImageResource(R.mipmap.img_ocr_back)
            binding.ocrDriverLicenseLayout.maskBack.visibility = View.GONE
            binding.ocrDriverLicenseLayout.imgUploadBack.setImageResource(R.mipmap.img_ocr_upload)
            binding.ocrDriverLicenseLayout.textUploadBack.text = getString(R.string.process_ocr_upload)
            binding.ocrDriverLicenseLayout.textUploadBack.setTextColor("#FF999999".toColorInt())

            //ELECTIONCARD
            binding.ocrElectionCardLayout.ocrElectionCardLayout.visibility = View.GONE
            binding.ocrElectionCardLayout.imgFront.setImageResource(R.mipmap.img_ocr_front)
            binding.ocrElectionCardLayout.maskFront.visibility = View.GONE
            binding.ocrElectionCardLayout.imgUploadFront.setImageResource(R.mipmap.img_ocr_upload)
            binding.ocrElectionCardLayout.textUploadFront.text = getString(R.string.process_ocr_upload)
            binding.ocrElectionCardLayout.textUploadFront.setTextColor("#FF999999".toColorInt())
            binding.ocrElectionCardLayout.imgBack.setImageResource(R.mipmap.img_ocr_back)
            binding.ocrElectionCardLayout.maskBack.visibility = View.GONE
            binding.ocrElectionCardLayout.imgUploadBack.setImageResource(R.mipmap.img_ocr_upload)
            binding.ocrElectionCardLayout.textUploadBack.text = getString(R.string.process_ocr_upload)
            binding.ocrElectionCardLayout.textUploadBack.setTextColor("#FF999999".toColorInt())

            //no_documents
            binding.ocrNoDocumentsLayout.ocrNoDocumentsLayout.visibility = View.GONE

            when(selectItem?.optString("type")){//"IDCARD","PASSPORT","DRIVING","ELECTIONCARD","NONE"
                "IDCARD" -> {
                    binding.ocrIdCardLayout.ocrIdCardLayout.visibility = View.VISIBLE
                }
                "PASSPORT" -> {
                    binding.ocrPassportLayout.ocrPassportLayout.visibility = View.VISIBLE
                }
                "DRIVING" -> {
                    binding.ocrDriverLicenseLayout.ocrDriverLicenseLayout.visibility = View.VISIBLE
                }
                "ELECTIONCARD" -> {
                    binding.ocrElectionCardLayout.ocrElectionCardLayout.visibility = View.VISIBLE
                }
                else -> {
                    binding.ocrNoDocumentsLayout.ocrNoDocumentsLayout.visibility = View.VISIBLE
                    binding.submitApprovedTipsLayout.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 点击选择图片
     */
    private fun onSikadwaUpdateClickListener(v: View){
        when(v.id){
            _binding?.ocrIdCardLayout?.frontLayout?.id -> {//身份证 正面
                isFront = true
                showPhotoDialog("IdCard Front")
            }
            _binding?.ocrIdCardLayout?.backLayout?.id -> {//身份证 反面
                isFront = false
                showPhotoDialog("IdCard Back")
            }
            _binding?.ocrPassportLayout?.imgView?.id -> {//护照
                isFront = true
                showPhotoDialog("Passport")
            }
            _binding?.ocrDriverLicenseLayout?.frontLayout?.id -> {//驾驶证 正面
                isFront = true
                showPhotoDialog("DriverLicense Front")
            }
            _binding?.ocrDriverLicenseLayout?.backLayout?.id -> {//驾驶证 反面
                isFront = false
                showPhotoDialog("DriverLicense Back")
            }
            _binding?.ocrElectionCardLayout?.frontLayout?.id -> {//选举卡 正面
                isFront = true
                showPhotoDialog("ElectionCard Front")
            }
            _binding?.ocrElectionCardLayout?.backLayout?.id -> {//选举卡 反面
                isFront = false
                showPhotoDialog("ElectionCard Back")
            }
        }
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(eventRemark: String){
        val photoDialog = PhotoDialog(context,eventRemark,object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                addEvent(EventType.CLICK.CLICK_CAMERA,eventRemark)
                onOpenCamera()
            }
            override fun openAlbum() {
                addEvent(EventType.CLICK.CLICK_ALBUM,eventRemark)
                onOpenAlbum()
            }
        })
        photoDialog.show()
    }

    /**
     * 拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                HHLog.e(">>>>>>onActivityResult: data = " + result.data)
                val imgPath = result.data?.getStringExtra("imgLocalPath")
                if (imgPath != null){
                    showSikadwaSelectedImageCallback(imgPath)
                }
            }
        }
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
        val intent = Intent(context, CameraOcrActivity::class.java)
        takePhotoResultLauncher.launch(intent)
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 选择图片、拍照成功
     */
    private fun showSikadwaSelectedImageCallback(imgPath: String) {
        if (selectItem == null){
            return
        }
        uploadImageAction(imgPath)
        _binding?.let { binding ->
            when(selectItem?.optString("type")){
                "IDCARD" -> {//身份证
                    if (isFront){
                        ImageUtil.instance?.loadImageUrl(context,binding.ocrIdCardLayout.imgFront,imgPath)
                        binding.ocrIdCardLayout.maskFront.visibility = View.VISIBLE
                        binding.ocrIdCardLayout.imgUploadFront.setImageResource(R.mipmap.img_ocr_re_upload)
                        binding.ocrIdCardLayout.textUploadFront.text = getString(R.string.process_ocr_re_upload)
                        binding.ocrIdCardLayout.textUploadFront.setTextColor("#FFFFFFFF".toColorInt())
                    } else {
                        ImageUtil.instance?.loadImageUrl(context,binding.ocrIdCardLayout.imgBack,imgPath)
                        binding.ocrIdCardLayout.maskBack.visibility = View.VISIBLE
                        binding.ocrIdCardLayout.imgUploadBack.setImageResource(R.mipmap.img_ocr_re_upload)
                        binding.ocrIdCardLayout.textUploadBack.text = getString(R.string.process_ocr_re_upload)
                        binding.ocrIdCardLayout.textUploadBack.setTextColor("#FFFFFFFF".toColorInt())
                    }
                }
                "PASSPORT" -> {//护照
                    ImageUtil.instance?.loadImageUrl(context,binding.ocrPassportLayout.imgView,imgPath)
                    binding.ocrPassportLayout.maskView.visibility = View.VISIBLE
                    binding.ocrPassportLayout.imgUpload.setImageResource(R.mipmap.img_ocr_re_upload)
                    binding.ocrPassportLayout.textUpload.text = getString(R.string.process_ocr_re_upload)
                    binding.ocrPassportLayout.textUpload.setTextColor("#FFFFFFFF".toColorInt())
                }
                "DRIVING" -> {//驾驶证
                    if (isFront){
                        ImageUtil.instance?.loadImageUrl(context,binding.ocrDriverLicenseLayout.imgFront,imgPath)
                        binding.ocrDriverLicenseLayout.maskFront.visibility = View.VISIBLE
                        binding.ocrDriverLicenseLayout.imgUploadFront.setImageResource(R.mipmap.img_ocr_re_upload)
                        binding.ocrDriverLicenseLayout.textUploadFront.text = getString(R.string.process_ocr_re_upload)
                        binding.ocrDriverLicenseLayout.textUploadFront.setTextColor("#FFFFFFFF".toColorInt())
                    } else {
                        ImageUtil.instance?.loadImageUrl(context,binding.ocrDriverLicenseLayout.imgBack,imgPath)
                        binding.ocrDriverLicenseLayout.maskBack.visibility = View.VISIBLE
                        binding.ocrDriverLicenseLayout.imgUploadBack.setImageResource(R.mipmap.img_ocr_re_upload)
                        binding.ocrDriverLicenseLayout.textUploadBack.text = getString(R.string.process_ocr_re_upload)
                        binding.ocrDriverLicenseLayout.textUploadBack.setTextColor("#FFFFFFFF".toColorInt())
                    }
                }
                "ELECTIONCARD" -> {//选举卡
                    if (isFront){
                        ImageUtil.instance?.loadImageUrl(context,binding.ocrElectionCardLayout.imgFront,imgPath)
                        binding.ocrElectionCardLayout.maskFront.visibility = View.VISIBLE
                        binding.ocrElectionCardLayout.imgUploadFront.setImageResource(R.mipmap.img_ocr_re_upload)
                        binding.ocrElectionCardLayout.textUploadFront.text = getString(R.string.process_ocr_re_upload)
                        binding.ocrElectionCardLayout.textUploadFront.setTextColor("#FFFFFFFF".toColorInt())
                    } else {
                        ImageUtil.instance?.loadImageUrl(context,binding.ocrElectionCardLayout.imgBack,imgPath)
                        binding.ocrElectionCardLayout.maskBack.visibility = View.VISIBLE
                        binding.ocrElectionCardLayout.imgUploadBack.setImageResource(R.mipmap.img_ocr_re_upload)
                        binding.ocrElectionCardLayout.textUploadBack.text = getString(R.string.process_ocr_re_upload)
                        binding.ocrElectionCardLayout.textUploadBack.setTextColor("#FFFFFFFF".toColorInt())
                    }
                }
                else -> {

                }
            }
        }
    }

    /**
     * 提交成功提示
     */
    private fun showIdCardSubmitDeleteInformationTipsDialog(params: JSONObject){
        val sendSuccessDialog = SubmitSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(false)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showSubmitSuccess(getString(R.string.process_face_submit_success_tips))
        lifecycleScope.launch {
            delay(1500)
            if (isAdded && !requireActivity().isFinishing && sendSuccessDialog.isShowing) {
                sendSuccessDialog.dismiss()
            }
            val act = context as ProcessActivity
            act.submitAction(params)
        }
    }

    /**
     * 上传图片
     */
    private fun uploadImageAction(imgPath: String){
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.FILE)
        uploadFileAction(httpUrl, File(imgPath),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                data.optJSONObject("obj")?.let {
                    val imgUrl = it.optString("url")
                    val ocrType = selectItem?.optString("type")
                    if (isFront){
                        imgFrontUrl = imgUrl
                        addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "$ocrType Front ：$imgUrl")
                    } else {
                        imgBackUrl = imgUrl
                        addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "$ocrType Back ：$imgUrl")
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshedProcess(event: String){
        when(event){
            Configs.Event.PROCESS_DATA_SUB -> {//上级点击提交
                onSikadwaSubOcrDataAction()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        stepItem?.let {
            addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_END,it.optString("stepTitle")),"")
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}